﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;
using System.Windows.Forms;
using WinSCP;
using System.Text.RegularExpressions;
using Renci.SshNet;

namespace winscpFtp
{
    public partial class Form1 : Form
    {
        // Implements the manual sorting of items by column.
        class ListViewItemComparer : IComparer
        {
            private int col;
            private SortOrder order;
            public ListViewItemComparer()
            {
                col = 0;
                order = SortOrder.Ascending;
            }
            public ListViewItemComparer(int column, SortOrder order)
            {
                col = column;
                this.order = order;
            }
            public int Compare(object x, object y)
            {
                ListViewItem itemX = x as ListViewItem;
                ListViewItem itemY = y as ListViewItem;
                // 保持第一个项不变
                if (itemX.Text.Equals(".."))
                    return -1; // 确保第一项始终在最前
                if (itemY.Text.Equals(".."))
                    return 1; // 确保第一项始终在最前
                int returnVal = -1;
               
                returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text,
                                        ((ListViewItem)y).SubItems[col].Text);
                // Determine whether the sort order is descending.
                if (order == SortOrder.Descending)
                    // Invert the value returned by String.Compare.
                    returnVal *= -1;
                return returnVal;
            }
        
        }
        public Form1()
        {
            InitializeComponent();
        }
        private int sortColumn = -1;
        SessionOptions sessionOptions;
        WinSCP.Session session;
        TransferOperationResult transferResult = null;
        TransferOptions transferOptions = new TransferOptions();
        RemoteDirectoryInfo remoteDirectoryInfo;
        ListViewItem listView1ItemRoot;

        public static bool ValidateIPAddress(string ipAddress)
        {
            Regex validipregex = new Regex(@"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
            return (ipAddress != "" && validipregex.IsMatch(ipAddress.Trim())) ? true : false;
        }
        //连接
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            //检查ip格式
            bool isIp = ValidateIPAddress(textBox1.Text.Trim());
            if (!isIp)
            {
                MessageBox.Show("请输入正确的ip！");
                return;
            }
            // 配置会话选项
            sessionOptions = new SessionOptions
            {
               // Protocol = Protocol.Scp,
                HostName = textBox1.Text,
                UserName = textBox2.Text,
                Password = textBox3.Text,
                PortNumber =Convert.ToInt32( textBox4.Text),
                 //SshHostKeyFingerprint = "ssh-rsa 1024 ll0iqW5PjitSqcb1JuI3pHXOhehkMmHLcKRg1Ijm0JY=",
               // SshHostKeyFingerprint = "ssh-rsa 1024 ZoU0fHT9xO+4QMxSYJlpebu5xgHPilV3wuAk0diF1AQ=",

            };
            switch (comboBox3.Text)
            {
                case "Sftp":
                    sessionOptions.Protocol = Protocol.Sftp;
                   
                    break;
                case "Scp":
                    sessionOptions.Protocol = Protocol.Scp;
                   
                    break;
                case "Ftp":
                    sessionOptions.Protocol = Protocol.Ftp;
                    break;
                default:
                    break;
            }
            if (comboBox3.Text.Equals("Sftp") || comboBox3.Text.Equals("Scp"))
            {
                    sessionOptions.AddRawSettings("KEX", "dh-group1-sha1,ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN");
            }
            //sessionOptions.SshHostKeyPolicy = SshHostKeyPolicy.Check;
            //sessionOptions.SshHostKeyPolicy = SshHostKeyPolicy.AcceptNew;
            //sessionOptions.SshHostKeyPolicy = SshHostKeyPolicy.GiveUpSecurityAndAcceptAny;
            getRemoteeDirectoryInfo(comboBox2.Text, comboBox3.Text);

            //上传下载enable
            contextMenuStripLocal.Items[0].Enabled = true;
            contextMenuStripLocal.Items[1].Enabled = true;
            contextMenuStripRemote.Items[0].Enabled = true;
            contextMenuStripRemote.Items[1].Enabled = true;
        }

        //获取ftp所有目录
        private void getRemoteeDirectoryInfo(string remotePath,string Protocol)
        {
            using (session = new WinSCP.Session())
            {
                try
                {
                    if (Protocol.Equals("Sftp") || Protocol.Equals("Scp"))
                    {
                            //sessionOptions.AddRawSettings("KEX", "dh-group1-sha1,ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN");
                            string SshHostKeyFingerprint1 = session.ScanFingerprint(sessionOptions, "SHA-256");
                            LogHelper.WriteLog("SshHostKeyFingerprint====" + SshHostKeyFingerprint1);
                            sessionOptions.SshHostKeyFingerprint = SshHostKeyFingerprint1;
                    }
                    // 连接
                    session.Open(sessionOptions);
                    // Upload files
                    transferOptions.TransferMode = TransferMode.Binary;
                    //获取所有目录
                    remoteDirectoryInfo = session.ListDirectory(remotePath);
                    // remoteDirectoryInfo = session.ListDirectory(".");
                    int fileCount = remoteDirectoryInfo.Files.Count;
                    Console.WriteLine(fileCount);
                    listView2Show(fileCount);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
       
        //listview2 显示,ftp端
        private void listView2Show(int fileCount)
        {
            listView2.Items.Clear();
            for (int i = 0; i < fileCount; i++)
            {
                if (!remoteDirectoryInfo.Files[i].Name.Equals("."))
                {
                    ListViewItem listViewItem = new ListViewItem();
                    listViewItem.Text = remoteDirectoryInfo.Files[i].Name;//文件名称
                    ListViewItem.ListViewSubItem listViewSubItem = new ListViewItem.ListViewSubItem();
                    listViewSubItem.Text = remoteDirectoryInfo.Files[i].LastWriteTime.ToString();//文件时间
                    ListViewItem.ListViewSubItem listViewSubItem2 = new ListViewItem.ListViewSubItem();
                    listViewSubItem2.Text = (remoteDirectoryInfo.Files[i].Length / 1024).ToString();//文件大小
                    ListViewItem.ListViewSubItem listViewSubItem3 = new ListViewItem.ListViewSubItem();
                    listViewSubItem3.Text = remoteDirectoryInfo.Files[i].FileType.ToString();//文件类型
                    listViewItem.SubItems.Add(listViewSubItem);
                    listViewItem.SubItems.Add(listViewSubItem2);
                    listViewItem.SubItems.Add(listViewSubItem3);
                    listView2.Items.Add(listViewItem);
                }
               
            }
           
        }

        


        //listview1 显示，本地端
        private void listView1Show(string path)
        {
            
            try
            {
                string[] fileEntries = Directory.GetFiles(path);
                string[] subdirectoryEntries = Directory.GetDirectories(path);
               


                listView1.Items.Clear();
                 listView1ItemRoot = new ListViewItem();
                listView1ItemRoot.Text = "..";
                ListViewItem.ListViewSubItem listViewRootSubItem = new ListViewItem.ListViewSubItem();
                listViewRootSubItem.Text = "";
                ListViewItem.ListViewSubItem listViewRootSubItem2 = new ListViewItem.ListViewSubItem();
                listViewRootSubItem2.Text = "";
                ListViewItem.ListViewSubItem listViewRootSubItem3 = new ListViewItem.ListViewSubItem();
                listViewRootSubItem3.Text = "";

                listView1ItemRoot.SubItems.Add(listViewRootSubItem);
                listView1ItemRoot.SubItems.Add(listViewRootSubItem2);
                listView1ItemRoot.SubItems.Add(listViewRootSubItem3);
                listView1.Items.Add(listView1ItemRoot);

                foreach (string fileName in fileEntries)
            {
                ListViewItem listViewItem = new ListViewItem();
                listViewItem.Text = new FileInfo(fileName).Name;
                ListViewItem.ListViewSubItem listViewSubItem = new ListViewItem.ListViewSubItem();
                listViewSubItem.Text = File.GetCreationTime(fileName).ToString();
                ListViewItem.ListViewSubItem listViewSubItem2 = new ListViewItem.ListViewSubItem();
                listViewSubItem2.Text = (new FileInfo(fileName).Length / 1024).ToString();
                ListViewItem.ListViewSubItem listViewSubItem3 = new ListViewItem.ListViewSubItem();
                listViewSubItem3.Text = MimeMapping.GetMimeMapping(fileName);
               
                    listViewItem.SubItems.Add(listViewSubItem);
                listViewItem.SubItems.Add(listViewSubItem2);
                listViewItem.SubItems.Add(listViewSubItem3);
                listView1.Items.Add(listViewItem);
            }

            foreach (string directoryName in subdirectoryEntries)
            {
                ListViewItem listViewItem = new ListViewItem();
                listViewItem.Text = new DirectoryInfo(directoryName).Name;
                    ListViewItem.ListViewSubItem listViewSubItem = new ListViewItem.ListViewSubItem();
                listViewSubItem.Text = Directory.GetCreationTime(directoryName).ToString();
                ListViewItem.ListViewSubItem listViewSubItem2 = new ListViewItem.ListViewSubItem();
                listViewSubItem2.Text = "0";
                ListViewItem.ListViewSubItem listViewSubItem3 = new ListViewItem.ListViewSubItem();
                listViewSubItem3.Text = "文件夹";
                //listViewSubItem3.Text = new DirectoryInfo(directoryName).Attributes.GetType().ToString();
                listViewItem.SubItems.Add(listViewSubItem);
                listViewItem.SubItems.Add(listViewSubItem2);
                listViewItem.SubItems.Add(listViewSubItem3);
                listView1.Items.Add(listViewItem);
            }

            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
            }

        }

     

        private void listView1_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
        {
            // Determine whether the column is the same as the last column clicked.
            if (e.Column != sortColumn)
            {
                // Set the sort column to the new column.
                sortColumn = e.Column;
                // Set the sort order to ascending by default.
                listView1.Sorting = SortOrder.Ascending;
            }
            else
            {
                // Determine what the last sort order was and change it.
                if (listView1.Sorting == SortOrder.Ascending)
                    listView1.Sorting = SortOrder.Descending;
                else
                    listView1.Sorting = SortOrder.Ascending;
            }

            // Call the sort method to manually sort.
            listView1.Sort();
            // Set the ListViewItemSorter property to a new ListViewItemComparer
            // object.
            this.listView1.ListViewItemSorter = new ListViewItemComparer(e.Column,
                                                              listView1.Sorting);
          
        }

        private void listView2_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
        {
            // Determine whether the column is the same as the last column clicked.
            if (e.Column != sortColumn)
            {
                // Set the sort column to the new column.
                sortColumn = e.Column;
                // Set the sort order to ascending by default.
                listView2.Sorting = SortOrder.Ascending;
            }
            else
            {
                // Determine what the last sort order was and change it.
                if (listView2.Sorting == SortOrder.Ascending)
                    listView2.Sorting = SortOrder.Descending;
                else
                    listView2.Sorting = SortOrder.Ascending;
            }

            // Call the sort method to manually sort.
            listView2.Sort();
            // Set the ListViewItemSorter property to a new ListViewItemComparer
            // object.
            this.listView2.ListViewItemSorter = new ListViewItemComparer(e.Column,
                                                              listView2.Sorting);
        }

        /// <summary>
        /// 断开连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            button1.Enabled = true;
            session.Dispose();
            
            listView2.Items.Clear();
            //上传下载enable
            contextMenuStripLocal.Items[0].Enabled = false;
            contextMenuStripLocal.Items[1].Enabled = false;

            contextMenuStripRemote.Items[0].Enabled = false;
            contextMenuStripRemote.Items[1].Enabled = false;

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Text = System.AppDomain.CurrentDomain.BaseDirectory;
            // 获取指定路径下所有文件夹和文件

            listView1Show(comboBox1.Text);
            string[] comboSubitems = new string[10];
            string desktop =  Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            comboSubitems[0] = desktop;
            
            DriveInfo[] allDirves = DriveInfo.GetDrives();
            //检索计算机上的所有逻辑驱动器名称
            int i = 1;
            foreach (DriveInfo item in allDirves)
            {
                comboSubitems[i] = item.Name;
                Console.Write(item.Name + "---" + item.DriveType);
                i++;
            }
            

            comboBox1.Items.AddRange(comboSubitems.Take(i).ToArray());


        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            listView1Show(comboBox1.Text);
        }

       

        private void 上传ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                using (session = new WinSCP.Session())
                {
                    // 连接
                    session.Open(sessionOptions);
                    // Upload files
                    transferOptions.TransferMode = TransferMode.Binary;
                    string localPath = comboBox1.Text + listView1.SelectedItems[0].Text;
                    string remoptejPath = comboBox2.Text;
                   
                    transferResult = session.PutFiles(localPath, remoptejPath, false, transferOptions);
                    // Throw on any error
                    transferResult.Check();
                    // Print results
                    foreach (TransferEventArgs transfer in transferResult.Transfers)
                    {
                        Console.WriteLine("Download of {0} succeeded", transfer.FileName);
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
            getRemoteeDirectoryInfo(comboBox2.Text, comboBox3.Text);
        }

        private void 下载ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                using (session = new WinSCP.Session())
                {
                    // 连接
                    session.Open(sessionOptions);

                    // Upload files

                    transferOptions.TransferMode = TransferMode.Binary;


                    string srcPath = comboBox2.Text + listView2.SelectedItems[0].Text;
                    string objPath = comboBox1.Text;
                    transferResult = session.GetFiles(srcPath, objPath, false, null);
                    // Throw on any error
                    transferResult.Check();

                    // Print results
                    foreach (TransferEventArgs transfer in transferResult.Transfers)
                    {
                        Console.WriteLine("Download of {0} succeeded", transfer.FileName);
                    }
                    listView1Show(comboBox1.Text);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
           
        }

        //本地路径双击
        private void listView1_mouseDouble(object sender, MouseEventArgs e)
        {
            if (listView1.SelectedItems[0].Text.Equals("..") || listView1.SelectedItems[0].Text.Equals("."))
            {
                int num = comboBox1.Text.LastIndexOf('\\');
                if (num>2)
                {
                    
                    comboBox1.Text = comboBox1.Text.Substring(0, num);
                    int num1 = comboBox1.Text.LastIndexOf('\\');
                    comboBox1.Text = comboBox1.Text.Substring(0, num1 + 1);
                   
                }
                
            }
            else
            {
                comboBox1.Text = comboBox1.Text + listView1.SelectedItems[0].Text + @"\";
                
            }
            listView1Show(comboBox1.Text);

        }
        //远程路径刷新
        private void listView2_mouseDouble(object sender, MouseEventArgs e)
        {
            if (listView2.SelectedItems[0].Text.Equals(".."))
            {
                int num = comboBox2.Text.LastIndexOf('/');
                if (num > 1)
                {

                    comboBox2.Text = comboBox2.Text.Substring(0, num);
                    int num1 = comboBox2.Text.LastIndexOf('/');
                    comboBox2.Text = comboBox2.Text.Substring(0, num1 + 1);
                   
                }

            }
            else
            {
                comboBox2.Text = comboBox2.Text + listView2.SelectedItems[0].Text + "/";
                
            }
            getRemoteeDirectoryInfo(comboBox2.Text, comboBox3.Text);


        }

        private void 刷新ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            getRemoteeDirectoryInfo(comboBox2.Text, comboBox3.Text);
        }

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView1Show(comboBox1.Text);
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void listView2_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {
            getRemoteeDirectoryInfo("..","Sftp");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            getRemoteeDirectoryInfo(".", "Sftp");
        }
    }
}
